<template>
  <el-table
    :data="data"
    border
    @row-click="handleRowClick"
    :row-key="getRowKeys" 
    :expand-row-keys="expands"
    @expand-change="handleExpandChange"
    style="width: 100%;margin-top:15px">
    <el-table-column type="expand" v-if="data.children && data.children.length > 0">
      <expand-table  :data="data.children"/>
    </el-table-column>
    <el-table-column label="Dimension">
      <template slot-scope="scope">
        {{scope.row.name !== null ? scope.row.name : 'null'}}
      </template>
    </el-table-column>
    <el-table-column label="Measure">
      <template slot-scope="scope">
        {{scope.row.value}}
      </template>
    </el-table-column>
    <el-table-column label="Operation" width="140px">
      <template slot-scope="scope" v-if="scope.row.children && scope.row.children.length > 0">
        <el-button type="text" @click="handleClearChildren(scope.row)">Clear Children</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script>
export default {
  name:'expandTable',
  props:{
    data:{
      type:Array,
      default:() => {
        return []
      }
    }
  },
  components:{ ExpandTable:() => import('./expand-table.vue') },
  watch:{
    data:{
      handler:function(val){
        this.recursionChildren(val)
      },
      deep:true
    }
  },
  data(){
    return {
      expands: [], 
      getRowKeys: (row) => { 
          return row.name + row.value; 
      }
    }
  },
  methods:{
    handleExpandChange(row,expandedRows){
      let that = this;
      if (expandedRows.length) {
          that.expands = []
          if (row) {
              that.expands.push(row.name + row.value)
          }
      } else {
          that.expands = []
      }
    },
    handleRowClick(row,column,event){
      this.$emit('row-click',row,column,event)
    },
    handleClearChildren(row){
      this.$set(row,'children',[])
    },
    recursionChildren(data){
      data.forEach((item) => {
        const _v = item.value
        if(item.children && item.children.length > 0){
          const sums = item.children.reduce((prev,cur) => {
            return (prev.value ? parseFloat(prev.value) : prev) + parseFloat(cur.value)
          })
          if(item.value !== sums){
            this.$set(item,'oldValue',_v)
            this.$set(item,'value',sums)
          }
          this.recursionChildren(item.children)
        }else{
          if(item.oldValue) {
            this.$set(item,'value',item.oldValue)
            delete item.oldValue
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>